var app = getApp()
var util = require('../../utils/util.js')
var bmap = require('../../utils/bmap-wx.min.js')
let now = util.getStamp(util.formatTime(new Date()));
const server = app.globalData.server;
var interstitialAd = null;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    data: '',
    shop: '',
    equipment: '',
    serialNumber:'',
    img: [],
    activation: false,
    avatarUrl: 'https://img10.360buyimg.com/ddimg/jfs/t1/164224/33/3176/1736/6005080bE0d9ade5b/c768fb7219e855f9.png',
    nickName: '用户昵称',
    card: 'xxx xxx xxxx',
    memberName: '',
    extend: 0,
    brand: '',
    model: '',
    height: '440rpx',
    complete:0,
    z:-1,
    noticeName: 'notice',
    seconds: 6,
  },

  countTime() {
    let that = this;
    let seconds = that.data.seconds-1;
    //console.log(seconds)
    if (seconds > 0) {
      that.setData({
        seconds
      })
      setTimeout(that.countTime, 1000);
    } else {
      that.setData({
        seconds: 0
      })
    }
  },

  noticeModal(e) {
    this.setData({
      noticeName: 'notice'
    })
  },
  showModal(e) {
    this.setData({
      noticeName: ''
    })
  },



  //安装车型
  toChoose: function () {
    if (this.data.activation == false) {
      wx.navigateTo({
        url: '../inactivated/chooseBrand/chooseBrand',
      })
    }
  },

  ChooseImage() {
    wx.chooseImage({
      count: 1, //默认9
      sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], //从相册选择
      success: (res) => {
        console.log(res)
        this.setData({
          img: res.tempFilePaths
        })
        console.log(this.data.img)
      }
    });
  },

  ViewImage(e) {
    wx.previewImage({
      urls: this.data.img,
      current: this.data.img[e.target.dataset.index]
    });
  },

  DelImg(e) {
    let img = this.data.img;
    wx.showModal({
      content: '确定要删除图片吗？',
      cancelText: '取消',
      confirmText: '确定',
      success: res => {
        if (res.confirm) {
          img.splice(0, 1);
          this.setData({
            img
          })
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let userInfo = wx.getStorageSync('userInfo')
    console.log(userInfo.nickName + ":" + this.data.activation)
    var that = this;
    let isIphoneX = app.globalData.isIphoneX;
    console.log(isIphoneX)
    this.setData({
      isIphoneX,
      memberName: userInfo.nickName
    })

    that.countTime();
     if (wx.createInterstitialAd) {
      interstitialAd = wx.createInterstitialAd({
        adUnitId: 'adunit-5808a5fa513ac393'
      })
      interstitialAd.onLoad(() => {
        console.log(11111)
      })
      interstitialAd.onError((err) => {
        console.log(22222)
      })
      interstitialAd.onClose(() => {
        console.log(3333)
      })
    }

    if (options) {
      let code;
      console.log(options)
      if (options.data) {
        let data = JSON.parse(options.data)
        code = data.res_code;
        console.log(data)
        setTimeout(() => {
          this.setData({
            data: data,
            complete: 1
          })
          that.querystring(data.suffix,code)
        }, 0)
      }else{
        code = options.q.substring(options.q.length - 16)
        let u = '';
        u=util.getRandomCode(5)
        console.log(u)
        if (code == 'TBTXAVGU4OAkkkkk' || code == 'SZXC2VGU4OAkkkkk') {
          code = code.substring(0, 11) + u
        }
        console.log(code)
        util.request('/model/detail', {
          brand_code: code.substring(0, 1),
          category_code: code.substring(1, 3),
          model_code: code.substring(3, 5)
        }, "GET").then(res => {
          console.log(res)
          let list = res.data;
          if(list[0].brand_name=='神州行'){
            wx.setNavigationBarTitle({
              title: "神州行全国联保"
            })
          }else if(list[0].brand_name=='徒步天下'){
            wx.setNavigationBarTitle({
              title: "徒步天下全国联保"
            })
          }
          if (list.length == 0 ) {
            wx.showModal({
              title: '暂无该产品信息',
              showCancel: false,
              success: function (res) {
                if (res.confirm) {
                  wx.redirectTo({
                    url: '../index/index',
                  })
                }
              }
            })
          }
          list[0].res_code = code;
          that.setData({
            data: list[0],
            complete: 1
          })
          that.querystring(list[0].suffix,code)
        })
      }
      
    }
    if (!wx.getStorageSync('userInfo')) {
      setTimeout(() => {
        let profile;
        if (wx.getUserProfile) {
          profile=1;
        }else{
          profile=0;
        }
        this.selectComponent("#authorize").showModal(that.data.data.ml_bg,profile);
        this.retrieval()
      }, 2000)
    }
  },

  querystring(suffix,code){
    var that=this;
    util.request('/activation/detail', {
      data: code,
      suffix:suffix
    }, 'GET').then(res => {
      let data = res.data;
      console.log(res)
      if (data.length == 1) {
        wx.cloud.callFunction({
          name: 'login'
        }).then(res => {
          let openid = res.result.openid;
          console.log(openid)
          if (data[0].openid == openid) {
            that.setData({
              isOwner: true
            })
            wx.setNavigationBarTitle({
              title: "我的质保卡"
            })
          } else {
            that.setData({
              isOwner: false
            })
          }
        })
        let img = [];
        img.push(data[0].warranty_img)
        for (let i in img) {
          img[i] = app.globalData.fileSource + img[i];
        }
        that.setData({
          activation: true,
          card: data[0].warranty_card.substring(0, 3) + " " + data[0].warranty_card.substring(3, 6) + " " + data[0].warranty_card.substring(6),
          shop: data[0].warranty_shop,
          brand: data[0].warranty_car,
          img: img,
          equipment:data[0].equipment,
          serialNumber: data[0].device,
          nickName: data[0].nickName,
          avatarUrl: data[0].avatarUrl,
          start_date: data[0].start_date,
          end_date: data[0].end_date,
        })
      } else {
        that.setData({
          isOwner: true,
        })
        //暂只能激活一卡
        if (wx.getStorageSync('warranty')) {
          that.setData({
            //isOwner: false
          })
        }
        if (!that.data.activation) {
          that.setData({
            noticeName:''
          })
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (wx.getStorageSync('chooseBrand')) {
      let brand = wx.getStorageSync('chooseBrand')
      this.setData({
        brand: brand,
        modalName: 'brandConfirm',
        z: 200
      })
      wx.removeStorageSync('chooseBrand')
    }

    if (!wx.getStorageSync('brandList')) {
      var that = this;
      util.request('/car/name', {}, "GET").then(res => {
        let data = res.data;
        wx.setStorageSync('brandList', data)
      })
    }
  },
  inputShop: function (e) {
    this.setData({
      shop: e.detail.value
    })
  },
  inputEquipment: function (e) {
    this.setData({
      equipment: e.detail.value
    })
  },
  inputSerialNumber: function (e) {
    this.setData({
      serialNumber: e.detail.value
    })
  },
  inputBrand: function (e) {
    this.setData({
      brand: e.detail.value
    })
  },
  inputModel: function (e) {
    this.setData({
      model: e.detail.value
    })
  },
  hideModal(e) {
    this.setData({
      modalName: null,
      z: -1,
      checked: false
    })
  },
  async activation() {
    var that = this;
    if (wx.getStorageSync('userInfo')) {
      if (that.data.equipment == '') {
        wx.showToast({
          title: '产品不能为空',
          icon: 'none'
        })
        return
      }
      if (that.data.img == '') {
        wx.showToast({
          title: '请上传照片',
          icon: 'none'
        })
        return
      }
      if (that.data.brand == '') {
        wx.showToast({
          title: '请选择车型',
          icon: 'none'
        })
        return
      }
      if (that.data.shop == '') {
        wx.showToast({
          title: '门店不能为空',
          icon: 'none'
        })
        return
      }
      wx.showLoading({
        title: '激活中',
      })
      util.request('/activation/detail', {
        data: that.data.data.res_code,
        suffix: '_walk'
      }, "GET").then(res => {
        if (res.data.length == 0) {
          getApp().preventActive(async (res) => {
            if (!app.globalData.PageActive) {
              wx.uploadFile({
                url: server + '/upload/image', //仅为示例，非真实的接口地址
                filePath: that.data.img[0],
                name: 'file',
                formData: {
                  'catalog': 'entrucking'
                },
                success(res) {
                  console.log(res)
                  that.insert(res.data)
                 
                },
                fail: function (res) {
                  console.log(res)
                }
              })
            }
          })
        } else {
          wx.showToast({
            title: '该卡已被激活',
            icon: 'none'
          })
        }
      })
    } else {
      let profile;
      if (wx.getUserProfile) {
        profile=1;
      }else{
        profile=0;
      }
      this.selectComponent("#authorize").showModal(that.data.data.ml_bg,profile);
      this.retrieval()
    }
  },
  insert: function (image) {
    var that = this;
    wx.showLoading({
      title: '激活中',
    })

    let openid = 'nothing'
    let code = ''
    for (let e = 0; e < 10; e++) {
      code += Math.floor(Math.random() * 10)
    }
    let start = util.toDate(now, 'Y/M/D', 86400)
    let end = util.toDate(now, 'Y/M/D', 31536000 + 86400)
    let userInfo = wx.getStorageSync('userInfo')
    let info = {
      suffix: that.data.data.suffix,
      equipment: that.data.equipment,
      creation_date: util.formatTime(new Date()),
      creation_timestamp: Date.parse(util.formatTime(new Date()).replace(/-/g, '/')) / 1000,
      openid: app.globalData.openid,
      nickName: userInfo.nickName,
      avatarUrl: userInfo.avatarUrl,
      warranty_card: code,
      warranty_code: that.data.data.res_code,
      warranty_brand: that.data.data.brand_name,
      warranty_brand_code: that.data.data.res_code.substring(0, 1),
      warranty_category: that.data.data.category_name,
      warranty_category_code: that.data.data.res_code.substring(1, 3),
      warranty_model: that.data.data.model_name,
      warranty_model_code: that.data.data.res_code.substring(3, 5),
      warranty_shop: that.data.shop,
      warranty_car: that.data.brand + ' ' + that.data.model,
      sale_openid: openid,
      warranty_img: image,
      start_date: start,
      end_date: end,
      extend: 0
    };
    if(that.data.data.brand_code=='S'){
      info.device=that.data.serialNumber
    }
    util.request('/activation/insert', info, "POST").then(res => {
      console.log(res)
      wx.hideLoading({
        success: (res) => {},
      })
      wx.setStorageSync('warranty', info)
      that.setData({
        activation: true,
        start_date: start,
        end_date: end,
        card: code.substring(0, 3) + " " + code.substring(3, 6) + " " + code.substring(6),
        nickName: userInfo.nickName,
        avatarUrl: userInfo.avatarUrl,
        sale_openid: openid
      })
      wx.showToast({
        title: '激活成功',
        icon: 'success',
        duration: 2000
      })

      setTimeout(() => {
        interstitialAd.show().catch((err) => {
          console.error(err)
        })
      },2500)
      if (wx.pageScrollTo) {
        wx.pageScrollTo({
          scrollTop: 0
        })
      }
    })


  },
  async retrieval() {
    var that = this;
    let timing = setInterval(async () => {
      if (wx.getStorageSync('userInfo')) {
        setTimeout(() => {
          clearInterval(timing);
        }, 900);
      }
    }, 1000);
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: "品牌联保服务", 
      imageUrl: 'http://file.funiaopark.com/images/action/philips/public/public-1Vtgsi-676107.jpg', 
      path: '/pages/index/index'
    }
  }
})